package mysql

import (
	"fmt"
	"github.com/go-xorm/xorm"
	"github.com/pkg/errors"
	"strings"
	"time"
)

var ConsistencyType = map[string]string{
	"eventual": "非严格一致性",
	"session":  "最终一致性",
	"global":   "强一致性",
}

// 设置 Auraro 的写入转发的会话级别参数
func (h *Handler) setAuroraReplicaReadConsistency(ses *xorm.Session, mode string) (session *xorm.Session, err error) {
	// 1. 检查服务是否为正式环境 || 是否注入 Auraro 写入转发参数
	if (h.Mode != "test" && h.Mode != "release") || mode == "" {
		return ses, nil
	}
	// 2. 检查 Auraro 数据库写入转发模式是否合法
	mode = strings.ToLower(mode)
	if ConsistencyType[mode] == "" {
		return ses, errors.New("aurora_replica_read_consistency is abnormal：" + mode)
	}
	// 3. 执行服务
	var try bool
	sql := fmt.Sprintf(`set aurora_replica_read_consistency="%s"`, mode)
	for i := 0; i < 3; i++ {
		if session, err, try = h.trySet(ses, sql, i); !try {
			return
		}
		time.Sleep(1 * time.Second)
	}
	return ses, err
}

func (h *Handler) trySet(ses *xorm.Session, sql string, i int) (session *xorm.Session, err error, try bool) {
	// 1.执行 sql，设置配置
	_, err = ses.Exec(sql)
	if err != nil {
		return ses, err, false
	}
	// 2. 打印设置配置结果
	//if result != nil {
	//	lastId, err1 := result.LastInsertId()
	//	affected, err2 := result.RowsAffected()
	//	logger.Debug("set aurora_replica_read_consistency result",
	//		zap.Error(err1), zap.Error(err2), zap.Any("result", []interface{}{lastId, affected}))
	//}
	// 3. 查询配置信息
	res, err := ses.QueryString(`show session variables where variable_name like "aurora_replica_read_consistency"`)
	if err != nil || len(res) == 0 || len(res[0]) == 0 || res[0]["Value"] == "" {
		return ses, err, true
	}
	return ses, err, false
}
